//$(function(){
//	plusReady();
//});
function plusReady() {
    //初始化页面
    var id = getUrlParam("id");	//订单号
    var user = userLogin();			//用户
    //	var id = 95;
    //	var user = {"id":2,"name":"15158884139","email":"","nick":"掌创0002","real_name":"谢霆锋","avatar_id":0,"code":"03EA","id_no":"330184198406201352","id_pic1":2,"id_pic2":3,"id_pic3":2,"user_type":1,"status":1,"auth_status":0,"parent_id":0,"remark":null,"created_at":"2015-06-14 11:28:24","updated_at":"2015-06-14 11:29:18","token":"MnwkMnkkMTAkNDgvMEgxSlQvWlpyOFU0bVZEcmpYdW1jVDUyNjZFWTB6OUVrR3pnL0xvL00zSlF3MnZSbld8OGEyMTViNjM1YjhhYTJmOTZhOTc4MTgwYmE1NzEyNDk=","account":{"id":2,"user_id":2,"used":"0.00","all":"20050.00","cash":"10050.00","card":"10000.00","coin":"10000.00"}};
    PaintPage(id, user);
}
if (window.plus) {
    plusReady();
} else {
    document.addEventListener('plusready', plusReady, false);
}

//初始化页面
function PaintPage(id, user) {

    var postdata = { "userid": user.id, "token": user.token, "orderid": id };
	console.log(JSON.stringify(postdata));
    $.ajax({
        type: "POST",
        url: configManager.RequstUrl + "api/order/info",
        async: true,
        data: postdata
    }).done(function (data) {
        if ("success" == data.state) {
        	var order = data.data;
        	//如果是商家，判断是否自己的订单
        	if ( ([2,3].indexOf(user.user_type) > -1) && order.seller.code != user.code) { 
        		plus.nativeUI.alert("不是本店订单，不允许操作！"); back(); return; 
        	}
            Render(user, order);
            BindEvent(user, order);
        }
        else {
            plus.ui.alert(data.message, function () { }, configManager.alerttip, configManager.alertCtip);
        }
    });
}


function Render(user, order) {
    var html = []

    html.push('<div class="sjxqbkbg">');
    var src = '';
    $.each(order.goods, function (i, goods) {
        src = configManager.storeImgurl.format(goods.goods_pic, "")
        html.push('<dl style="font-size:1.2em;" class="dlsdlmx"><dt style="width:15%;"><a href="#"><img style="width:50px;height:50px" src="' + src + '" /></a></dt><dd>' + goods.goods_title + '</dd><dd>单价：<b>¥' + goods.goods_price + '元</b></dd>');
        if([2,3].indexOf(goods.goods_type) > -1){
        	html.push('<dd><span><a name="imagetext" tip="' + goods.goods_id + '">查看图文详情</a></span></dd>');
       	}
        html.push('</dl>');
    });
    if(1 == order.is_groupbuy){
    	html.push('<p class="sjxqsst"><span><b><img src="../../../images/sjxqtu4.png" /></b>支持随时退</span><span><b><img src="../../../images/sjxqtu5.png" /></b>支持过期退</span></p></div>');
   	}
    html.push('<div class="grxinxis ddxqym"><p class="sjxqmdkxyh"><span id="orderspan"><a>申请退款</a></span><font style="font-size:0.7em">下单时间：' + order.created_at + '</font></p></div>')
    
    html.push('<div class="sjxqbkbg sjxqckxq"><h2>订单详情</h2><p><b>订单号：</b>' + order.order_sn + '</p><p><b>购买手机号：</b>' + user.name + '</p><p><b>下单时间：</b>' + order.created_at + '</p><p><b>数量：</b>' + order.goods.length + '</p><p><b>总价：</b><span id="money">' + order.money + '</span>元</p></div>');
     
    html.push('<div class="sjxqbkbg sjxqckxq"><h2>商家信息</h2><p>' + order.seller.store.store_name + '</p><p>' + order.seller.store.store_address + '</p></div>')
    
    if(1 == order.is_groupbuy){
    	html.push('<div class="sjxqbkbg sjxqckxq"><h2>购买须知</h2><p><b class="zcd"></b>' + order.goods[0].goods_notice + '</p></div>');
	}
    html.push('<div class="sjxqbkbg sjxqckxq"><h2>本单详情</h2>');
    html.push('<p><b class="zcd">商家名称：</b>' + order.seller.store.store_name + '</p>');
    html.push('<p><b class="zcd">商品数量：</b>' + order.goods.length + '</p>');
    html.push('<p><b class="zcd">商品总价：</b>' + order.money + '元 </p>');
    html.push('</div>');

    

    html.push('</div>');

    $("#orderdetail").html(html.join(""));
}


//绑定事件
function BindEvent(user, order) {
    //普通用户
    if ( [1,4,5].indexOf(user.user_type) > -1 ) {
        if ("0" != order.payment) { //线上支付
            if ("0" == order.status) { //未付款可以点击支付
                $("#orderspan a").text("付款");
                $("#orderspan").on("click", function () {
                    payOrder(user, order);
                });
            }
            else if ("1" == order.status) {//已付款可以点击申请退款
                var ispresellorder = false;
                if (order.goods && order.goods.count > 0) {
                    $.each(order.goods, function (i, goods) { if (goods.goods_type == 2) { ispresellorder = true; return; } });
                }
                if (!ispresellorder) {
                    $("#orderspan a").text("退款");
                    $("#orderspan").on("click", function () {
                        refundOrder(user, order);
                    });
                }
            }
            else {
                //$("#orderspan").remove();
                showOrderStatus(order.status);
            }
        }
        else {
            //$("#orderspan").remove();
            showOrderStatus(order.status);
        }
    }
    //商家和商家子帐号
    else if ( [2,3].indexOf(user.user_type) > -1 ) {
        if ([-2].indexOf(order.status) > -1)			//退款
        {
            $("#orderspan a").text("同意退款");
            $("#orderspan").on("click", function () {
                confirmRefund(user, order);
            });
        }
//      else if( 1 == order.status || ( 0 == order.payment && 0 == order.status ) ){//确认消费
//          $("#money").css({"color":"#C41308", "font-size":"1.3em"}); 
//          $("#orderspan a").text("确认消费");
//          $("#orderspan").on("click", function () {
//          	confirmResume(user, order);
//          });
//      }
        else {
            //$("#orderspan").remove();
            showOrderStatus(order.status);
        }
    }
        //其他
    else {
        //$("#orderspan").remove();
        showOrderStatus(order.status);
    }

    //点击图文详情
    $("#orderdetail").on("click", "a[name=imagetext]", function () {
        var page = "../goods/imagetext.html?goodsid=" + $(this).attr('tip');
        clicked(page);
    });
}

//普通用户 线上支付 支付订单
function payOrder(user, order) {
    //构造一个临时订单跳转到支付界面

    //	//				console.log("更新前" + JSON.stringify(temporder) );
    //	temporder.id 		= data.data.id;
    //	temporder.amount	= postorder.amount;
    //	temporder.discount	= parseFloat($("#discount").text());
    //	temporder.total		= parseFloat($("#totalprice").text());
    //	temporder.storeid	= postorder.store;
    //	temporder.coin		= postorder.coin;	
    //	
    //	
    //  var currentgoods = {
    //      "id"		: goodinfo.id,
    //      "storeid"	: goodinfo.store.id,
    //      "title"		: goodinfo.title,
    //      "price"		: goodinfo.price,
    //      "pic"		: goodinfo.pic,
    //      "count"		: 1,
    //      "selected"	: true
    //  };

    var temporder = {};
    //商品
    temporder.goods = [];
    $.each(order.goods, function (i, goods) {

        temporder.goods.push({
            "id": goods.id,
            "storeid": goods.store_id,
            "title": goods.goods_title,
            "price": goods.goods_price,
            "pic": goods.goods_pic,
            "count": goods.quantity,
            "selected": true
        });
    });
    temporder.id = order.id;
    temporder.amount = order.amount;
    temporder.discount = order.pay_coin / configManager.coinrate;
    temporder.total = order.amount - temporder.discount;
    temporder.storeid = order.store_id;
    temporder.coin = order.pay_coin;
    plus.storage.setItem(storageManager.temporder, JSON.stringify(temporder));
    //直接支付
    //console.log("temporder:" + JSON.stringify(temporder));
    clicked('paytype.html');
}

//普通用户 线上支付 申请退款
function refundOrder(user, order) {

    var postdata = { "userid": user.id, "token": user.token, "order": order.id };
    $.ajax({
        type: "POST",
        url: configManager.RequstUrl + "api/order/refund",
        async: true,
        data: postdata
    }).done(function (data) {
        if ("success" == data.state) {
            plus.ui.alert(data.message, function () { clicked('order.html') }, configManager.alerttip, configManager.alertCtip);
        } else {
            plus.ui.alert(data.message, function () { }, configManager.alerttip, configManager.alertCtip);
        }
    });

}

//商家确认退款
function confirmRefund(user, order) {

    var postdata = { "userid": user.id, "token": user.token, "order": order.id };


    console.log("postdata=" + (postdata.token));

    $.ajax({
        type: "POST",
        url: configManager.RequstUrl + "api/store/orderrefund",
        async: true,
        data: postdata
    }).done(function (data) {
        if ("success" == data.state) {
            plus.ui.alert(data.message, function () { clicked('order.html') }, configManager.alerttip, configManager.alertCtip);
        } else {
            plus.ui.alert(data.message, function () { }, configManager.alerttip, configManager.alertCtip);
        }
    });

}

//商家确认消费
function confirmResume(user, order){
    var postdata = { "userid": user.id, "token": user.token, "order": order.id };
    //		console.log(JSON.stringify(postdata));
    //		return false;
    $.ajax({
        type: "POST",
        url: configManager.RequstUrl + "api/store/orderdone",
        async: true,
        data: postdata
    }).done(function (data) {
        if ("success" == data.state) {
            plus.ui.alert(data.message, function () { }, configManager.alerttip, configManager.alertCtip);
        } else {
            plus.ui.alert(data.message, function () { }, configManager.alerttip, configManager.alertCtip);
        }
    });	
}


function showOrderStatus(status){
	switch(status){
		case -3: //
			$("#orderspan").html("已退款");
			break;
		case -2:
			$("#orderspan").html("退款中");
			break;
		case -1:
			$("#orderspan").html("已取消");
			break;
		case 0:
			$("#orderspan").html("未付款");
			$("#money").css({"color":"#C41308", "font-size":"1.3em"});
			break;
		case 1:
			$("#orderspan").html("未消费");
			$("#money").css({"color":"#04AD5F", "font-size":"1.3em"});
			break;
		case 2:
			$("#money").css({"color":"#04AD5F", "font-size":"1.3em"});
			$("#orderspan").html("待评价");
			break;
		case 3:
			$("#money").css({"color":"#04AD5F", "font-size":"1.3em"});
			$("#orderspan").html("已完成");
			break;			
		default:
		break;
	}
}
